package cn.itcast.bos.web.action.common;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.springframework.data.domain.Page;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
    //模型驱动
    protected T model;
    @Override
    public T getModel() {
        return model;
    }
    //构造器完成model初始化
    public BaseAction(){
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Class<T> modelclass = (Class<T>) parameterizedType.getActualTypeArguments()[0];

        try {
            model = modelclass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            System.out.println("模型构造失败");
        }
    }

    //分页查询代码重构优化
    protected int page;
    protected int rows;

    public void setPage(int page) {
        this.page = page;
    }
    public void setRows(int rows) {
        this.rows = rows;
    }
    protected void pushPageDataToValueStrack(Page<T> pageData){
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",pageData.getTotalElements());
        map.put("rows",pageData.getContent());
        ActionContext.getContext().getValueStack().push(map);

    }
}
